package com.winit.openapi.ups.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.inbound.InboundOrderService;
import com.winit.oms.spi.inbound.command.InboundOrderEorDataCommand;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.EorIorInfoService;
import com.winit.ums.spi.commnad.EorIorInfoCommand;
import com.winit.ums.spi.vo.EorIorInfo;
import com.winit.ups.spi.customstrade.IorEorTypeService;
import com.winit.ups.spi.customstrade.command.QueryIorEorTypeForListCommand;
import com.winit.ups.spi.customstrade.vo.IorEorTypeVo;

@Controller
@RequestMapping(value = "/ups/iorEorType")
public class IorEorTypeController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(IorEorTypeController.class);

    @Resource
    private IorEorTypeService   iorEorTypeService;

    @Resource
    private EorIorInfoService   eorIorInfoService;
    
    @Resource
    private InboundOrderService inboundOrderService;

    @RequestMapping(value = "/queryIorEorTypeList")
    public String queryImportDeclarationRulesByCondition(@ModelAttribute RequestMsg requestMsg,
                                                         @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = null;
        if (requestMsg.getData() instanceof JSONObject) {
            json = JSONObject.parseObject(requestMsg.getData().toString());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 类型
        String type = (String) json.get("type");
        logger.info("类型：{}", type);

        // 查询
        QueryIorEorTypeForListCommand command = new QueryIorEorTypeForListCommand();
        command.setType(type);
        List<IorEorTypeVo> list = iorEorTypeService.queryByParamForList(command);

        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/queryEorDataByConditionList")
    public String queryEorDataByCondition(@ModelAttribute RequestMsg requestMsg,
                                          @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = null;
        if (requestMsg.getData() instanceof JSONObject) {
            json = JSONObject.parseObject(requestMsg.getData().toString());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 校验参数
        ValidateUtil.validNotNull(json, "endWarehouseCode");
        ValidateUtil.validNotNull(json, "productCode");

        // 获取【目的仓】编码
        String endWarehouseCode = (String) json.get("endWarehouseCode");
        
        // 获取产品编码
        String productCode = (String) json.get("productCode");

        InboundOrderEorDataCommand command = new InboundOrderEorDataCommand();
        command.setCtx(CommandContext.getContext());
        command.setEndWarehouseCode(endWarehouseCode);
        command.setProductCode(productCode);
        List<Map<String, Object>> resultList = inboundOrderService.queryEorDataList(command);
        responseMsg.setData(resultList);
        return SUCCESS;
    }

    @RequestMapping(value = "/queryEorDataByCountry")
    public String queryEorDataByCountry(@ModelAttribute RequestMsg requestMsg,
                                        @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = null;
        if (requestMsg.getData() instanceof JSONObject) {
            json = JSONObject.parseObject(requestMsg.getData().toString());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 校验参数
        ValidateUtil.validNotNull(json, "countryCode");

        // 获取国家编码
        String countryCode = (String) json.get("countryCode");

        List<Map<String, Object>> resultList = this.queryEorData(countryCode);

        responseMsg.setData(resultList);
        return SUCCESS;
    }

    /**
     * 查询出EOR类型并组装.
     * 
     * @param countryCode
     * @return
     */
    private List<Map<String, Object>> queryEorData(String countryCode) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

        // 先查询出所有的EOR类型
        QueryIorEorTypeForListCommand command = new QueryIorEorTypeForListCommand();
        command.setType("EOR");
        List<IorEorTypeVo> list = iorEorTypeService.queryByParamForList(command);

        if (list == null || list.size() == 0) {
            logger.info("未查询到EOR类型");
            return resultList;
        }

        // 遍历
        for (IorEorTypeVo iorEorTypeVo : list) {
            // 找到自有EOR
            if ("CEOR".equals(iorEorTypeVo.getCode())) {
                // 查询客户下所有的出口商
                EorIorInfoCommand eorIorInfoCommand = new EorIorInfoCommand();
                eorIorInfoCommand.setCtx(CommandContext.getContext());
                eorIorInfoCommand.setUserId(CommandContext.getContext().getUserId());
                eorIorInfoCommand.setType("EOR");
                eorIorInfoCommand.setCountryCode(countryCode);
                List<EorIorInfo> eorIorInfoList = eorIorInfoService.queryEorIorInfoByType(eorIorInfoCommand);

                // 去掉推荐出口商
                List<EorIorInfo> filterList = new ArrayList<EorIorInfo>();
                for (EorIorInfo eorIorInfo : eorIorInfoList) {
                    if ("Y".equals(eorIorInfo.getIsWinit())) {
                        continue;
                    }
                    filterList.add(eorIorInfo);
                }
                
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", iorEorTypeVo.getCode());
                map.put("name", iorEorTypeVo.getName());
                map.put("eors", filterList);
                resultList.add(map);
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", iorEorTypeVo.getCode());
                map.put("name", iorEorTypeVo.getName());
                map.put("eors", null);
                resultList.add(map);
            }
        }
        return resultList;
    }
}
